import React, { useState, useEffect } from 'react';
import { Card, Button, Space, Select, Input } from 'antd';
import request from './request';
import { getToken } from './utils/tools';
import { PAGE_SIZE, options } from './config';
import AddBook from './components/AddBook';
import BookList from './components/BookList';

function Manager() {

  const [openDrawer, setOpenDrawer] = useState(false);
  const [bookList, setBookList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [current, setCurrent] = useState(1);
  const [total, setTotal] = useState(0);

  const [searchVal, setSearchVal] = useState();
  const [categoryVal, setCategoryVal] = useState();
  const [curBook, setCurBook] = useState(null);

  const getBookList = (cur = current, category, name) => {
    setLoading(true);
    request.get('/api/list', {
      params: { current: cur, pageSize: PAGE_SIZE, category, name }
    }).then((data) => {
      const { list, total } = data;
      setBookList(list);
      setTotal(total);
    }).finally(() => {
      setLoading(false);
    });
  };

  useEffect(() => {
    getToken();
  }, []);

  useEffect(() => {
    let cur = current;
    if (searchVal || categoryVal) {
      cur = 1;
      setCurrent(cur);
    } else {
      getBookList(current, categoryVal, searchVal);
    }
  }, [current, searchVal, categoryVal]);

  const handleOpenDrawer = () => {
    setCurBook(null);
    setOpenDrawer(true);
  };

  const handlePaginationChange = (page) => {
    setCurrent(page);
  };

  const handleSelectChange = (value) => {
    setCategoryVal(value);
  };

  const handleSearch = (value) => {
    setSearchVal(value);
  };

  return (
    <div style={{width: 1400, margin: '16px auto'}}>
      <Card
        title="图书管理"
        extra={(
          <Space size="large">
            <Select
              allowClear
              options={options}
              style={{width: 160}}
              placeholder="类别"
              onChange={handleSelectChange}
            />
            <Input.Search placeholder="搜索" onSearch={handleSearch} />
            <Button type="primary" onClick={handleOpenDrawer}>添加图书</Button>
          </Space>
        )}
      >
        <AddBook
          curBook={curBook}
          setCurBook={setCurBook}
          getBookList={getBookList}
          isShow={openDrawer}
          setIsShow={setOpenDrawer}
        />

        <BookList
          total={total}
          list={bookList}
          current={current}
          loading={loading}
          pageSize={PAGE_SIZE}
          setCurBook={setCurBook}
          setBookList={setBookList}
          getBookList={getBookList}
          setOpenDrawer={setOpenDrawer}
          onPaginationChange={handlePaginationChange}
        />
      </Card>
    </div>
  );
}

export default Manager;
